//-------------------------------- request 对象定义----------------------------------------
var Request = new Object();
Request = GetRequest();
var request = Request;

//WebAPI调用地址
var ApiUrl = "http://" + location.host + "/AjaxModels";

//页面现场恢复变量名称：名称类似"cxFasb_list_params"形式；
var QueryParamsCookieName = "";

//前台
var ProcUrl = "http://" + location.host + "/Login.aspx";

//用户对象定义
var User = {
    Language: "", //选择语言
    OID: "", //OID
    UserNickName: "", //用户昵称 当用户昵称不存在的时候，显示用户名
    UserImage: "", //头像
    Token: "", //token对象...用户登陆唯一
};

function GetCookieUser() {
    var curuser = getcookie('curUser');
    if (curuser != null) {
        var obj = StrToJson(curuser);
        User.Language = obj.Language;
        User.OID = obj.OID;
        User.UserNickName = obj.UserNickName;
        User.UserImage = obj.UserImage;
        User.Token = obj.Token;
    }
}

/// <summary>
/// Ajax调用WebAPI
/// </summary>
/// <param name="aRouter">后台服务程序，如ashx文件</param>
/// <param name="aJsonParams">参数对象，用json对象表示，如：{"cmd": "get","key": aKey}</param>
/// <returns type="">返回经utf8解码后的字符串</returns>
function ApiPost(aRouter, aJsonParams, completeCallback) {
    var ApiRouter = ApiUrl + "/" + aRouter;
    var aObj = $.ajax({
        type: "post",
        url: ApiRouter,
        async: false, //采用同步方式获取数据
        data: aJsonParams,
        datatype: "text",
        statusCode: {
            500: function () {
                //console.log('500');
                layer.confirm('您尚未登录，请登录后再打开该页面', {
                    title: '系统信息',
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    //登录
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
                }, function () {
                });
                return;
            },
            600: function () {
                //600未登陆
                console.log('600未登录');
                layer.confirm('您尚未登录，请登录后再打开该页面', {
                    title: false, // '系统信息',
                    closeBtn: false,
                    btn: ['Yes'] //按钮
                }, function () {
                    //登录
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
                }, function () {
                });
                return;
            },
            601: function () {
                //601对应类名或方法不存在
                layer.alert('系统执行接口异常，请尝试重新打开或者联系系统管理员！', {
                    title: '系统消息',
                    closeBtn: 0,
                    icon: 2,
                    btn: '确定'
                });
            },
            602: function () {
                //602内部执行异常
                layer.alert('系统执行接口异常，请尝试重新打开或者联系系统管理员！！', {
                    title: '系统消息',
                    closeBtn: 0,
                    icon: 2,
                    btn: '确定'
                });
            },
            603: function () {
                //603用户SESSION不匹配
                layer.confirm('用户SESSION不匹配，请重新登录！', {
                    title: false, // '系统信息',
                    closeBtn: false,
                    btn: ['Yes'] //按钮
                }, function () {
                    //登录
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
                }, function () {
                });
            }
        }
    }).done(completeCallback);
    var r = aObj.responseText;

    var s = "";
    if (r != undefined && r != null) {
        s = r.toString();
    } else {
        return "-1";
    }
    //调用失败

    if (s == "99") {
        //跳转登录页面
        //登录
        try {
            parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
        } catch (e) {
            location.href = ProcUrl + '?url=' + escape(location.href);
        }
    } else {
        try {
            var objjjj = eval('(' + s + ')');
        } catch (e) {
            //跳转登录页面
            if (s.indexOf('Login.aspx') != -1) {
                //登录
                try {
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
                } catch (e) {
                    location.href = ProcUrl + '?url=' + escape(location.href);
                }
            }
        }
        var regex1 = new RegExp('u003cscript', 'g');
        var regex2 = new RegExp('u003escript', 'g');

        s = s.replace(regex1, "&lt;script");
        s = s.replace(regex2, "&gt;script");
        return s;
    }
}

function GetToken() {
    if ($('html').attr('XTOKEN') != undefined && $('html').attr('XTOKEN') != '') {
        return $('html').attr('XTOKEN');
    } else {
        return 'TOKENISUNDEFIND';
    }
}

/// <summary>
/// Ajax调用WebAPI
/// </summary>
/// <param name="aRouter">aspx页面后台对应的方法名称</param>
/// <param name="aJsonParams">参数对象，用json对象表示，如：{"cmd": "get","key": aKey}</param>
/// <param name="completeCallback">当延迟成功时调用一个函数或者数组函数.</param>
/// <returns type="">返回经utf8解码后的字符串</returns>
function ApiPostLogin(aRouter, aJsonParams, completeCallback) {
    var strFullPath = window.document.location.href;
    var strPath = window.document.location.pathname;
    var pos = strFullPath.indexOf(strPath);
    var prePath = strFullPath.substring(0, pos);
    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
    var webPath = prePath + postPath;
    var ARouter = webPath+aRouter;
    console.log(ARouter);
    var aObj = $.ajax({
        type: "post",
        url: ARouter,
        contentType: 'application/json', //这里必须指明要传递到服务器的内容的编码方式，而且必须是json,否则后台方法获取不到传递数据。
        async: false, //采用同步方式获取数据
        data: aJsonParams, //参数必须和后台的参数名称一样 data必须传递json格式的数据
        datatype: "json", //客户端以json的方式去读取返回数据
        statusCode: {
            600: function () {
                //600未登陆
                console.log('600未登录');
                layer.confirm('您尚未登录，请登录后再打开该页面', {
                    title: false, // '系统信息',
                    closeBtn: false,
                    btn: ['Yes'] //按钮
                }, function () {
                    //登录
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
                }, function () {
                });
                return;
            },
            601: function () {
                //601对应类名或方法不存在
                layer.alert('系统执行接口异常，请尝试重新打开或者联系系统管理员！', {
                    title: '系统消息',
                    closeBtn: 0,
                    icon: 2,
                    btn: '确定'
                });
            },
            602: function () {
                //602内部执行异常
                layer.alert('系统执行接口异常，请尝试重新打开或者联系系统管理员！！', {
                    title: '系统消息',
                    closeBtn: 0,
                    icon: 2,
                    btn: '确定'
                });
            },
            603: function () {
                //603用户SESSION不匹配
                layer.confirm('用户SESSION不匹配，请重新登录！', {
                    title: false, // '系统信息',
                    closeBtn: false,
                    btn: ['Yes'] //按钮
                }, function () {
                    //登录
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
                }, function () {
                });
            }
        }
    });
    return aObj.responseText;
}

/// <summary>
/// Ajax调用WebAPI	//截至到2019-4-26暂时没有调用//徐呈佩
/// </summary>
/// <param name="aRouter">aspx页面后台对应的方法名称</param>
/// <param name="aJsonParams">参数对象，用json对象表示，如：{"cmd": "get","key": aKey}</param>
/// <param name="completeCallback">成功后调用函数.</param>
/// <returns type="">返回经utf8解码后的字符串</returns>
function ApiPostLoginLoad(aRouter, aJsonParams, completeCallback) {
    //等待
    var $lload = layer.load(1);

    var nsp = 'VMA';
    nsp += '.Web';
    //获取页面
    var strBaseUrl = window.location.pathname;
    //将/转成.
    var nspUrl = strBaseUrl.replace(/\/\/\//g, "/").replace(/\/\//g, "/").replace(/\//g, ".");
    //拼装cln
    var strpath = nsp + nspUrl.substr(0, nspUrl.length - 5);

    var ApiRouter = ApiUrl + "/AspxHandler.ashx?cln=" + strpath + "&met=" + aRouter;


    var aObj = $.ajax({
        type: "post",
        url: ApiRouter,
        contentType: 'application/json', //这里必须指明要传递到服务器的内容的编码方式，而且必须是json,否则后台方法获取不到传递数据。
        async: true, //采用同步方式获取数据
        data: aJsonParams, //参数必须和后台的参数名称一样 data必须传递json格式的数据
        datatype: "json", //客户端以json的方式去读取返回数据
        statusCode: {
            600: function () {
                //600未登陆
                console.log('600未登录');
                layer.confirm('您尚未登录，请登录后再打开该页面', {
                    title: false,
                    closeBtn: false,
                    btn: ['Yes'] //按钮
                }, function () {
                    //登录
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);

                }, function () {
                });
                return;
            },
            601: function () {
                //601对应类名或方法不存在
                //console.log('601对应类名或方法不存在');
                //alert('601对应类名或方法不存在');
                layer.alert('系统执行接口异常，请尝试重新打开或者联系系统管理员！', {
                    title: '系统消息',
                    closeBtn: 0,
                    icon: 2,
                    btn: '确定'
                });
            },
            602: function () {
                //602内部执行异常
                //console.log('602内部执行异常');
                //alert('602内部执行异常');
                layer.alert('系统执行接口异常，请尝试重新打开或者联系系统管理员！！', {
                    title: '系统消息',
                    closeBtn: 0,
                    icon: 2,
                    btn: '确定'
                });
            },
            603: function () {
                //603用户SESSION不匹配
                layer.confirm('用户SESSION不匹配，请重新登录！', {
                    title: false, // '系统信息',
                    closeBtn: false,
                    btn: ['Yes'] //按钮
                }, function () {
                    //登录
                    parent.location.href = ProcUrl + '?url=' + escape(parent.location.href);
                }, function () {
                });
            }
        }
    }).done(function (data) {
        setTimeout(function () {
            layer.close($lload);
        }, 300);
        //console.log('接口调用成功');
        doCallback(eval(completeCallback), [data]);
    }).fail(function (data) {
        doCallback(eval(completeCallback), [data]);
        console.log('接口调用失败');
        setTimeout(function () {
            layer.close($lload);
        }, 300);
        layer.alert('系统执行接口异常，请尝试重新打开或者联系系统管理员！');
    });

}

/// <summary>
/// Ajax调用WebAPI
/// </summary>
/// <param name="aRouter">aspx页面后台对应的方法名称</param>
/// <param name="aJsonParams">参数对象，用json对象表示，如：{"cmd": "get","key": aKey}</param>
/// <param name="completeCallback">当延迟成功时调用一个函数或者数组函数.</param>
/// <returns type="">返回经utf8解码后的字符串</returns>
function ApiPostAspx(aRouter, aJsonParams, completeCallback) {
    var ApiRouter = GetPageName() + '/' + aRouter;
    var aObj = $.ajax({
        type: "post",
        url: ApiRouter,
        contentType: 'application/json', //这里必须指明要传递到服务器的内容的编码方式，而且必须是json,否则后台方法获取不到传递数据。
        async: false, //采用同步方式获取数据
        data: aJsonParams, //参数必须和后台的参数名称一样 data必须传递json格式的数据
        datatype: "json", //客户端以json的方式去读取返回数据
        statusCode: {
            601: function () {
                //601对应类名或方法不存在
                console.log('aspx_601对应类名或方法不存在');
                alert('aspx_601对应类名或方法不存在');

            },
            602: function () {
                //602内部执行异常
                console.log('aspx_602内部执行异常');
                alert('aspx_602内部执行异常');
            }
        }
    }).done(completeCallback);
    //因为webmethod的方法默认返回的数据格式是json的格式而且数据格式如："{'d':'返回的数据'}",所以要通过.d来获取返回的内容。
    //var r = aObj.responseText;
    return aObj.responseText;
}

//获取页面名称,带后缀
function GetPageName() {
    var strUrl = location.pathname.split("/");
    var strPage = strUrl[strUrl.length - 1];
    return strPage;
}

/// <summary>
/// 获取ＵＲＬ request对象,使用方法
/// var Request = new Object();
/// Request = GetRequest();
/// var 参数1, 参数2, 参数3, 参数N;
/// 参数1 = Request['参数1'];
/// 参数2 = Request['参数2'];
/// 参数3 = Request['参数3'];
/// 参数N = Request['参数N'];
/// </summary>
/// <returns type="">
///
/// </returns>
function GetRequest() {

    var url = location.search;
    //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

//-------------------------------- 字符串应用函数 --------------------------------------
//把字符串值从一对标识中取出，如：
//      s = "<value>这是一个返回值</value>";
//      var v = UnTagStr(s,"value");
//则v为：这是一个返回值
function UnTagStr(aStr, aTag) {
    var s = aStr;
    var tag1 = "<" + aTag + ">";
    var tag2 = "</" + aTag + ">";

    var i = s.indexOf(tag2);
    if (i != -1) {
        s = s.substring(0, i);
        i = s.indexOf(tag1);
        if (i != -1) {
            s = s.substring(i, s.length);
            s = s.replace(tag1, "");
        }
    }
    return s;
}

function toaMessage(msg, msgtype, poo) {
    //toast-top-full-width
    //toast-bottom-full-width
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": poo,
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };

    /*  positionClass
     var positions = {
        top_right:"toast-top-right",
        bottom_right:"toast-bottom-right",
        bottom_left:"toast-bottom-left",
        top_left:"toast-top-left",
        top_full_width:"toast-top-full-width",
        bottom_full_width:"toast-bottom-full-width",
        top_center:"toast-top-center",
        bottom_center:"toast-bottom-center"
    };
     */
    if (msgtype == "info") {
        toastr.info(msg);
    }
    if (msgtype == "success") {
        toastr.success(msg);
    }
    if (msgtype == "warning") {
        toastr.warning(msg);
    }
    if (msgtype == "error") {
        toastr.error(msg);
    }
}

function getcookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) {
        return null;
    }
    var end = document.cookie.indexOf(';', len);
    if (end == -1) {
        end = document.cookie.length;
    }
    var cvalue = unescape(document.cookie.substring(len, end));

    return cvalue; //unescape(document.cookie.substring(len, end));
}

/// <summary>
/// 保存cookie变量
/// </summary>
/// <param name="name">变量名称</param>
/// <param name="value">变量值</param>
/// <param name="expires">过期天数</param>
/// <param name="path">路径</param>
/// <param name="domain">域</param>
/// <param name="secure">安全</param>
function setcookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + '=' + escape(value) + ((expires) ? ';expires=' + expires_date.toGMTString() : '') + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ((secure) ? ';secure' : '');
}

//把字符串对象转换为json对象，以便于访问
function StrToJson(aStr) {
    if (aStr == "") {
        return null;
    }
    var obj = '';
    try {
        obj = JSON.parse(aStr);
    } catch (e) {
        console.log(e)
        try {
            obj = eval('(' + aStr + ')');
        } catch (e1) {
            console.log(e1)
            obj = undefined;
        }
    }
    return obj;
}

function JsonToStr(aJson) {
    //把json对象转换为字符串,以便于传输
    //var str = $.toJSON(aJson);
    var str = JSON.stringify(aJson);
    return str;
}

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;

    if (len) {
        // Compact form
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        // rfc4122, version 4 form
        var r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return uuid.join('');
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//时间戳转成时间格式
function getLocalTime(nS) {
    //return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');
    return new Date(parseInt(nS) * 1000);
    //2016/5/29 上午8:00:

}

/**
 ajaxUrl:调用接口的地址
 params:接口调用参数,包括tag
 controlID:分页控件ID
 */
function jqPagingInit(ajaxUrl, params, controlID, callback) {
    var result = ApiPost(ajaxUrl, params);
    if (result != -1) {
        var obj = eval('(' + result + ')');
        //这里可以做填充了
        //settable(obj);
        if (!obj.records || obj.records == 0) {
            obj.records = 1;
        } else if (parseInt(obj.total) < params.page) {
            params.page = parseInt(obj.total);
        }

        doCallback(eval(callback), [obj]);

        //初始化jqPaginator插件
        $('#' + controlID).jqPaginator({
            totalCounts: parseInt(obj.records), //设置分页的总条目数
            pageSize: params.rows, //设置每一页的条目数
            visiblePages: params.maxpages, //设置最多显示的页码数
            currentPage: params.page, //设置当前的页码
            first: '<li class="first"><a href="javascript:void(0);"><span class="glyphicon glyphicon-step-backward" ><\/span><\/a><\/li>',
            prev: '<li class="prev"><a href="javascript:void(0);"><i class="arrow arrow2"><\/i><span class="glyphicon glyphicon-chevron-left" ><\/span><\/a><\/li>',
            next: '<li class="next"><a href="javascript:void(0);"><span class="glyphicon glyphicon-chevron-right" ><\/span><i class="arrow arrow3"><\/i><\/a><\/li>',
            last: '<li class="last"><a href="javascript:void(0);"><span class="glyphicon glyphicon-step-forward" ><\/span><\/a><\/li>',
            page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
            onPageChange: function (num, type) {
                //$('#text').html('当前第' + num + type+'页');
                if (type == 'change') {
                    params.page = num;

                    var newresult = ApiPost(ajaxUrl, params);
                    var obj = JsonToStr(newresult);
                    //settable(obj);
                    var paramsStr = JsonToStr(params);
                    setParams(QueryParamsCookieName, paramsStr);
                    doCallback(eval(callback), [obj]);
                }
            }
        });
    }

}

/**
 ajaxUrl:调用接口的地址
 params:接口调用参数,包括tag
 controlID:分页控件ID
 */
function jqPagingInitLogin(ajaxUrl, params, controlID, callback, queryParCookieName) {
    var result = ApiPostLogin(ajaxUrl, JsonToStr(params));
    if (result != -1) {
        var obj = StrToJson(result);
        //这里可以做填充了
        //settable(obj);
        if (!obj.records || obj.records == 0) {
            obj.records = 1;
        } else if (parseInt(obj.total) < params.page) {
            params.page = parseInt(obj.total);
        }
        var paramsStr = JsonToStr(params);
        if (queryParCookieName != undefined) {
            setParams(queryParCookieName, paramsStr);
        } else {
            setParams(QueryParamsCookieName, paramsStr);
        }

        doCallback(eval(callback), [obj]);

        //初始化jqPaginator插件
        $('#' + controlID).jqPaginator({
            totalCounts: parseInt(obj.records), //设置分页的总条目数
            pageSize: params.rows, //设置每一页的条目数
            visiblePages: params.maxpages, //设置最多显示的页码数
            currentPage: params.page, //设置当前的页码
            first: '<li class="first"><a href="javascript:void(0);"><span class="glyphicon glyphicon-step-backward" ><\/span><\/a><\/li>',
            prev: '<li class="prev"><a href="javascript:void(0);"><i class="arrow arrow2"><\/i><span class="glyphicon glyphicon-chevron-left" ><\/span><\/a><\/li>',
            next: '<li class="next"><a href="javascript:void(0);"><span class="glyphicon glyphicon-chevron-right" ><\/span><i class="arrow arrow3"><\/i><\/a><\/li>',
            last: '<li class="last"><a href="javascript:void(0);"><span class="glyphicon glyphicon-step-forward" ><\/span><\/a><\/li>',
            page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
            onPageChange: function (num, type) {
                //$('#text').html('当前第' + num + type+'页');
                if (type == 'change') {
                    params.page = num;
                    var newresult = ApiPostLogin(ajaxUrl, JsonToStr(params));
                    var obj = StrToJson(newresult);
                    //settable(obj);
                    var paramsStr = JsonToStr(params);
                    if (queryParCookieName != undefined) {
                        setParams(queryParCookieName, paramsStr);
                    } else {
                        setParams(QueryParamsCookieName, paramsStr);
                    }

                    doCallback(eval(callback), [obj]);
                }
            }
        });
    }

}

function doCallback(fn, args) {
    fn.apply(this, args);
}

function jqPagingGotoPage(controlID, gosize) {
    $('#' + controlID).jqPaginator('option', {
        currentPage: gosize
    });

    params.page = gosize;

    var newresult = ApiPostLogin(ajaxUrl, JsonToStr(params));
//		var newresult = ApiPost(ajaxUrl, params);
    var obj = StrToJson(newresult);

    var paramsStr = JsonToStr(params);
    if (queryParCookieName != undefined) {
        setParams(queryParCookieName, paramsStr);
    } else {
        setParams(QueryParamsCookieName, paramsStr);
    }

    doCallback(eval(callback), [obj]);
//		settable(obj);
}

//保存页面查询条件参数
function setParams(guidName, jsonStr) {
    //setcookie(guidName, jsonStr);
    window.localStorage[guidName] = jsonStr;
}

//获取页面查询条件参数的json字符串
function getParams(guidName) {
    //var paramsStr = getcookie(guidName);
    var paramsStr = window.localStorage[guidName];

    var paramsJson;
    if (!paramsStr) {
        return undefined;
    }
    paramsJson = StrToJson(paramsStr);
    return paramsJson;
}

function getExplorer() {
    var explorer = window.navigator.userAgent;
    //ie
    if (explorer.indexOf("MSIE") >= 0) {
        //alert("ie");
        return "ie";
    }
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        return "ie"; //IE
    }
    //firefox
    else if (explorer.indexOf("Firefox") >= 0) {
        //alert("Firefox");
        return "firefox";
    }
    //Chrome
    else if (explorer.indexOf("Chrome") >= 0) {
        //alert("Chrome");
        return "chrome";
    }
    //Opera
    else if (explorer.indexOf("Opera") >= 0) {
        //alert("Opera");
        return "opera";
    }
    //Safari
    else if (explorer.indexOf("Safari") >= 0) {
        //alert("Safari");
        return "safari";
    }
}

function htmlEncode(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    s = s.replace(/\n/g, "<br>");
    return s;
}

function htmlDecode(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/<br>/g, "\n");
    return s;
}

/**
 * 强制限制开始日期与结束日期
 * 参数1开始日期控件ID       参数2结束日期控件ID
 */
function ConstraintStartEndTime(StartControl, EndControl, StartJson, EndJson) {

    if (StartJson == undefined || StartJson == '' || StartJson == null) {
        StartJson = {
            format: 'yyyy/mm/dd',
            autoclose: true,
            todayHighlight: true,
            todayBtn: true,
            minView: 'month'
        };
    }
    if (EndJson == undefined || EndJson == '' || EndJson == null) {
        EndJson = {
            format: 'yyyy/mm/dd',
            autoclose: true,
            todayHighlight: true,
            todayBtn: true,
            //				pickerPosition:'bottom-left',
            minView: 'month'
        };
    }
    $("#" + StartControl).datetimepicker(StartJson).on('changeDate', function (e) {
        //console.log('选择开始时间：');
        //设置结束日期的 开始时间为当前的开始时间
        $("#" + EndControl).datetimepicker('setStartDate', e.date);
    });

    //开始时间。。。显示的时候 ，开始时间的结束时间是  结束控件时间
    $("#" + StartControl).datetimepicker().on('show', function (e) {
        $("#" + StartControl).datetimepicker('setEndDate', new Date($("#" + EndControl).val()));
    });

    $("#" + EndControl).datetimepicker(EndJson).on('changeDate', function (e) {
        //console.log('选择结束时间：');
        var stime = $("#" + StartControl).val();
        var etime = e.date;
        if (new Date(stime) > new Date(etime)) {
            $("#" + EndControl).val('');
            layer.msg('开始时间大于结束时间');
            return;
        }
        //设置开始时间的  结束日期是当前的结束时间
        $("#" + StartControl).datetimepicker('setEndDate', e.date);
    });
    $("#" + EndControl).datetimepicker().on('show', function (e) {
        $("#" + EndControl).datetimepicker('setStartDate', new Date($("#" + StartControl).val()));
    });

    var $stime = $("#" + StartControl).val();
    if ($stime != '' && $stime != undefined) {
        //console.log('$stime'+$stime);
        $("#" + EndControl).datetimepicker('setStartDate', new Date($stime));

    }
    var $etime = $("#" + EndControl).val();
    if ($etime != '' && $etime != undefined) {
        //console.log('$etime'+$etime);
        $("#" + StartControl).datetimepicker('setEndDate', new Date($etime));
    }

}


/**
 * 强制限制开始日期与结束日期
 * 参数1开始日期控件ID       参数2结束日期控件ID
 */
function ConstraintStartEndTimeForDOM(StartControlDOM, EndControlDOM, StartJson, EndJson) {

    if (StartJson == undefined || StartJson == '' || StartJson == null) {
        StartJson = {
            format: 'yyyy/mm/dd',
            autoclose: true,
            todayHighlight: true,
            todayBtn: true,
            minView: 'month'
        };
    }
    if (EndJson == undefined || EndJson == '' || EndJson == null) {
        EndJson = {
            format: 'yyyy/mm/dd',
            autoclose: true,
            todayHighlight: true,
            todayBtn: true,
            minView: 'month'
        };
    }
    StartControlDOM.datetimepicker(StartJson).on('changeDate', function (e) {
        //console.log('选择开始时间：');
        //设置结束日期的 开始时间为当前的开始时间
        EndControlDOM.datetimepicker('setStartDate', e.date);
    });

    //开始时间。。。显示的时候 ，开始时间的结束时间是  结束控件时间
    StartControlDOM.datetimepicker().on('show', function (e) {
        StartControlDOM.datetimepicker('setEndDate', new Date(EndControlDOM.val()));
    });

    EndControlDOM.datetimepicker(EndJson).on('changeDate', function (e) {
        //console.log('选择结束时间：');
        var stime = StartControlDOM.val();
        var etime = e.date;
        if (new Date(stime) > new Date(etime)) {
            EndControlDOM.val('');
            layer.msg('开始时间大于结束时间');
            return;
        }
        //设置开始时间的  结束日期是当前的结束时间
        StartControlDOM.datetimepicker('setEndDate', e.date);
    });
    EndControlDOM.datetimepicker().on('show', function (e) {
        EndControlDOM.datetimepicker('setStartDate', new Date(StartControlDOM.val()));
    });

    var $stime = StartControlDOM.val();
    if ($stime != '' && $stime != undefined) {
        //console.log('$stime'+$stime);
        EndControlDOM.datetimepicker('setStartDate', new Date($stime));

    }
    var $etime = EndControlDOM.val();
    if ($etime != '' && $etime != undefined) {
        //console.log('$etime'+$etime);
        StartControlDOM.datetimepicker('setEndDate', new Date($etime));
    }
}

//模块打开时，记录日志---后面统计
//	$(function(){
//
//		if(GetRequest().menu!=undefined){
//			var result = ApiPost('SystemFramework/Login/login.ashx',
//		        { "tag":"pageinit","data":GetRequest().menu },0
//		   );
//		}
//	});

//限制所有的input[nuber] 输入框不能输入非数字(比如e)
$('input[type=number]').keypress(function (e) {
    if (!String.fromCharCode(e.keyCode).match(/[\d]/)) {
        return false;
    }
});

function userAgent() {
    var NV = {};
    var UA = navigator.userAgent.toLowerCase();
    try {
        NV.name = UA.indexOf("msie") > -1 ? "ie" :
            UA.indexOf("trident") > 0 ? "trident" :
                UA.indexOf("firefox") > 0 ? "firefox" :
                    UA.indexOf("chrome") > 0 ? "chrome" :
                        window.opera ? "opera" :
                            window.openDatabase ? "safari" :
                                "unkonw";
    } catch (e) {
    }
    try {
        NV.version = NV.name == "ie" ? UA.match(/msie ([\d.]+)/)[1] :
            NV.name == "trident" ? UA.match(/trident\/([\d.]+)/)[1] :
                NV.name == "firefox" ? UA.match(/firefox\/([\d.]+)/)[1] :
                    NV.name == "chrome" ? UA.match(/chrome\/([\d.]+)/)[1] :
                        NV.name == "opera" ? UA.match(/opera.([\d.]+)/)[1] :
                            NV.name == "safari" ? UA.match(/version\/([\d.]+)/)[1] :
                                "0";
    } catch (e) {
    }
    try {
        NV.shell = UA.indexOf("360ee") > -1 ? "360极速浏览器" :
            UA.indexOf("360se") > -1 ? "360安全浏览器" :
                UA.indexOf("aoyou") > -1 ? "遨游浏览器" :
                    UA.indexOf("theworld") > -1 ? "世界之窗浏览器" :
                        UA.indexOf("worldchrome") > -1 ? "世界之窗极速浏览器" :
                            UA.indexOf("greenbrowser") > -1 ? "绿色浏览器" :
                                UA.indexOf("qqbrowser") > -1 ? "QQ浏览器" :
                                    UA.indexOf("baidu") > -1 ? "百度浏览器" :
                                        UA.indexOf("se") > -1 ? "搜狗浏览器" :
                                            UA.indexOf("MSIE") > -1 ? "IE浏览器" :
                                                UA.indexOf("edge") > -1 ? "微软edge浏览器" :
                                                    "谷歌浏览器";
    } catch (e) {
    }

    NV.userAgent = UA;

    return NV;
}

function postclient() {
    if (window.localStorage['mac_id'] == undefined || window.localStorage['mac_id'] == '') {
        window.localStorage['mac_id'] = guid();
        // 取浏览器信息
        var postJson = {
            "tag": "client",
            "mac_id": window.localStorage['mac_id'].toString(),
            "uat": JsonToStr(userAgent()),
        }
        console.log('postclient');
        $.ajax({
            type: "post",
            url: ApiUrl + '/DeskTop/connector.ashx',
            data: postJson,
            datatype: "text",
        });
    }
}

$(function () {

    postclient();

});